package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseAppV1;
import com.atguigu.gmall.realtime.bean.TrafficHomeDetailPageViewBean;
import com.atguigu.gmall.realtime.common.Constant;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/5/3 8:00
 */
public class Dws_03_DwsTrafficPageViewWindowApp extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_03_DwsTrafficPageViewWindowApp().init("Dws_3_DwsTrafficPageViewWindowApp",
                                                      4003,
                                                      1,
                                                      "Dws_3_DwsTrafficPageViewWindowApp",
                                                      "Dws_3_DwsTrafficPageViewWindowApp",
                                                      Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        /*
            找出访问首页和详情页的独立访客数
            
        
         */
        
        
        // 1. 解析数据, 并鉴别出独立访客数: 首页和详情页
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> uvStream = findUv(stream);
        // 2. 开窗聚合
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> aggregatedStream = windowAndAgg(uvStream);
        // 3. 写出到clickhouse中
        writeToClickHouse(aggregatedStream);
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> aggregatedStream) {
        aggregatedStream.addSink(FlinkSinkUtil.getClickHouseSink("gmall2022", "dws_traffic_page_view_window", TrafficHomeDetailPageViewBean.class));
        
    }
    
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> windowAndAgg(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> uvStream) {
        // 这次聚合没有维度, 也就是不用 keyBy
        // 这次聚合所有的数据在一起聚合, 所以可以用全窗口函数: 只有一个并行度
      return  uvStream
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
            .reduce(
                new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean v1,
                                                                TrafficHomeDetailPageViewBean v2) throws Exception {
                        v1.setHomeUvCt(v1.getHomeUvCt() + v2.getHomeUvCt());
                        v1.setGoodDetailUvCt(v1.getGoodDetailUvCt() + v2.getGoodDetailUvCt());
                        return v1;
                    }
                },
                new ProcessAllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<TrafficHomeDetailPageViewBean> elements,
                                        Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        TrafficHomeDetailPageViewBean bean = elements.iterator().next();
                        
                        bean.setStt(DateFormatUtil.toYmdHms(ctx.window().getStart()));
                        bean.setEdt(DateFormatUtil.toYmdHms(ctx.window().getEnd()));
                        
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                        
                    }
                }
            );
        
        
    }
    
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> findUv(DataStreamSource<String> stream) {
        
        
        return stream
            .map(JSON::parseObject)
            .filter(obj -> { // 过滤出首页 和 商品详情页数据
                String pageId = obj.getJSONObject("page").getString("page_id");
                return "home".equals(pageId) || "good_detail".equals(pageId);
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .process(new KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>() {
                
                private ValueState<String> goodDetailState;
                private ValueState<String> homeState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    homeState = getRuntimeContext().getState(new ValueStateDescriptor<String>("homeState", String.class));
                    goodDetailState = getRuntimeContext().getState(new ValueStateDescriptor<String>("goodDetailState", String.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                    long homeUvCt = 0L;
                    long goodDetailUvCt = 0L;
                    Long ts = obj.getLong("ts");
                    
                    String today = DateFormatUtil.toDate(ts);
                    String yesterday = homeState.value();
                    
                    String pageId = obj.getJSONObject("page").getString("page_id");
                    
                    if ("home".equals(pageId) && !today.equals(yesterday)) {
                        //1. 如果pageId 是home, 且home状态为null或非今天, 则把homeUvCt 置为1
                        homeUvCt = 1L;
                        homeState.update(today);
                        
                    } else if ("good_detail".equals(pageId) && !today.equals(yesterday)) {
                        // 2. 否则, 判断goodDetail状态
                        goodDetailUvCt = 1L;
                        goodDetailState.update(today);
                    }
                    
                    if (homeUvCt != 0 || goodDetailUvCt != 0) {
                        out.collect(new TrafficHomeDetailPageViewBean("", "",
                                                                      homeUvCt, goodDetailUvCt,
                                                                      ts
                        ));
                    }
                    
                    
                }
            });
        
    }
}
